package com.xinbochuang.machine.admin.controller.system;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicResponseParameters;
import com.xinbochuang.machine.admin.domain.macRoom.MacRoom;
import com.xinbochuang.machine.admin.domain.plan.CheckPlan;
import com.xinbochuang.machine.admin.domain.plan.CheckPlanRoom;
import com.xinbochuang.machine.admin.domain.plan.CheckRoomCabinet;
import com.xinbochuang.machine.admin.domain.system.SysUser;
import com.xinbochuang.machine.admin.domain.vo.EquCabinetVo;
import com.xinbochuang.machine.admin.domain.vo.EquipmentVo;
import com.xinbochuang.machine.admin.domain.vo.MacRoomVo;
import com.xinbochuang.machine.admin.dto.PlanListDto;
import com.xinbochuang.machine.admin.mapper.plan.EquCabinetVoMapper;
import com.xinbochuang.machine.admin.mapper.plan.EquipmentVoMapper;
import com.xinbochuang.machine.admin.mapper.plan.MacRoomVoMapper;
import com.xinbochuang.machine.admin.service.plan.ICheckPlanRoomService;
import com.xinbochuang.machine.admin.service.plan.ICheckPlanService;
import com.xinbochuang.machine.admin.service.plan.ICheckRoomCabinetService;
import com.xinbochuang.machine.common.controller.BaseController;
import com.xinbochuang.machine.common.domain.LoginUser;
import com.xinbochuang.machine.common.domain.TableDataInfo;
import com.xinbochuang.machine.common.utils.AESUtils;
import com.xinbochuang.machine.common.utils.ServletUtils;
import com.xinbochuang.machine.framework.web.domain.AjaxResult;
import com.xinbochuang.machine.framework.web.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 核查计划
 *
 * @author 黄晓鹏
 * @date 2020-09-10 16:48
 */
@Api(value = "核查计划接口", position = 10, protocols = "http")
@RestController
@RequestMapping("/system/plan")
public class SysPlanController extends BaseController {

    @Resource
    private ICheckPlanService checkPlanService;

    @Resource
    private MacRoomVoMapper roomVoMapper;

    @Resource
    private EquCabinetVoMapper cabinetVoMapper;

    @Resource
    private EquipmentVoMapper equipmentVoMapper;

    @Resource
    private ICheckRoomCabinetService roomCabinetService;
    @Resource
    private TokenService tokenService;

    @Resource
    private ICheckPlanRoomService checkPlanRoomService;

    @Resource
    private ICheckRoomCabinetService checkRoomCabinetService;

//    /**
//     * 获取计划列表(废弃)
//     */
//    @PreAuthorize("@ss.hasPermi('system:plan:list')")
//    @GetMapping("/list")
//    public TableDataInfo list(CheckPlan checkPlan) {
//        return checkPlanService.selectPlanList(checkPlan);
//    }

    /**
     * 获取计划列表
     */
//    @PreAuthorize("@ss.hasPermi('system:plan:list')")
    @GetMapping("/list")
    public TableDataInfo list(CheckPlan checkPlan) {
        startPage();
        return getDataTable(checkPlanService.selectPlanRoomList(checkPlan));
    }

    /**
     * 获取计划下机房列表
     */
    //@PreAuthorize("@ss.hasPermi('system:plan:list')")
    @GetMapping("/planMacRoomList")
    public AjaxResult planMacRoomList(CheckPlan checkPlan) {
        List<PlanListDto> result = checkPlanService.planMacRoomList(checkPlan);
        Integer totalCount = checkPlanService.planMacRoomCount(checkPlan);
        return AjaxResult.data(result, totalCount);
    }

    /**
     * 根据类型获取核查资源子节点
     */
    @PreAuthorize("@ss.hasPermi('system:plan:add')")
    @GetMapping("/getRes")
    public AjaxResult getRes(String type, String uuid) {
        if (StrUtil.isBlank(uuid)) {
            //查询机房
            List<MacRoomVo> roomVoList = roomVoMapper.selectList(null);
            return AjaxResult.data(roomVoList);
        } else {
            if ("room".equals(type)) {
                //查询机柜
                List<EquCabinetVo> cabinetVoList = cabinetVoMapper.selectList(new QueryWrapper<EquCabinetVo>().eq("MAC_ID", uuid));
                return AjaxResult.data(cabinetVoList);
            } else {
                //查询设备
                List<EquipmentVo> equipmentVoList = equipmentVoMapper.selectList(new QueryWrapper<EquipmentVo>().eq("CABINET_ID", uuid));
                return AjaxResult.data(equipmentVoList);
            }
        }
    }

    /**
     * 获取全部核查资源子节点
     */
    @PreAuthorize("@ss.hasPermi('system:plan:add')")
    @GetMapping("/getResAll")
    public AjaxResult getResAll() {
        //查询机房
        SysUser user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        List<MacRoomVo> roomVoList = roomVoMapper.selectList(new QueryWrapper<MacRoomVo>().eq("DEPT_ID", user.getDeptId()));
        for (MacRoomVo macRoomVo : roomVoList) {
            //查询机柜
            List<EquCabinetVo> cabinetVoList = cabinetVoMapper.selectList(new QueryWrapper<EquCabinetVo>().eq("MAC_ID", macRoomVo.getUuid()));
            macRoomVo.setChildren(cabinetVoList);
            for (EquCabinetVo equCabinetVo : cabinetVoList) {
                //查询设备
                List<EquipmentVo> equipmentVoList = equipmentVoMapper.selectList(new QueryWrapper<EquipmentVo>().eq("CABINET_ID", equCabinetVo.getUuid()));
                equCabinetVo.setChildren(equipmentVoList);
            }
        }
        return AjaxResult.data(roomVoList);
    }

    /**
     * 新增计划
     */
    @PreAuthorize("@ss.hasPermi('system:plan:add')")
    @PostMapping
    public AjaxResult add(@RequestBody CheckPlan checkPlan) {
        checkPlan.setUuid(UUID.fastUUID().toString());
        checkPlan.setCreateTime(DateUtil.now());
        return toAjax(checkPlanService.addPlan(checkPlan));
    }

    /**
     * 根据计划编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:plan:query')")
    @GetMapping(value = "/{uuid}")
    public AjaxResult getInfo(@PathVariable String uuid) {
        CheckPlan checkPlan = new CheckPlan();
        checkPlan.setUuid(uuid);
        TableDataInfo tableDataInfo = checkPlanService.selectPlanList(checkPlan);
        checkPlan = (CheckPlan) tableDataInfo.getRows().get(0);
        return AjaxResult.data(checkPlan);
    }

    /**
     * 修改计划
     */
    @PreAuthorize("@ss.hasPermi('system:plan:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody CheckPlan checkPlan) {
        return toAjax(checkPlanService.updatePlan(checkPlan));
    }

    /**
     * 审核
     */
    @PreAuthorize("@ss.hasPermi('system:plan:check')")
    @PutMapping("/check")
    public AjaxResult check(@RequestBody CheckPlan checkPlan) {
        return toAjax(checkPlanService.updateById(checkPlan));
    }

    /**
     * 核查状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:plan:edit')")
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody CheckRoomCabinet roomCabinet) {
        boolean result = roomCabinetService.update(roomCabinet, Wrappers.<CheckRoomCabinet>lambdaQuery()
                .eq(CheckRoomCabinet::getPlanId, roomCabinet.getPlanId())
                .eq(CheckRoomCabinet::getRoomId, roomCabinet.getRoomId())
                .eq(CheckRoomCabinet::getCabinetId, roomCabinet.getCabinetId()));
        return toAjax(result);
    }

    /**
     * 删除计划
     */
    @PreAuthorize("@ss.hasPermi('system:plan:remove')")
    @DeleteMapping("/{uuid}")
    public AjaxResult remove(@PathVariable("uuid") String uuid) {
        return toAjax(checkPlanService.deletePlan(uuid));
    }


    /**
     * app获取计划列表
     */
    /**
     * app登录方法
     *
     * @return 结果
     */
    @ApiOperation(value = "app获取计划列表", consumes = "application/json", response = AjaxResult.class)
    @ApiImplicitParams({
    })
    @ApiOperationSupport(
            responses = @DynamicResponseParameters(properties = {
                    @DynamicParameter(value = "状态码", name = "code", dataTypeClass = int.class, example = "200"),
                    @DynamicParameter(value = "是否成功", name = "status", dataTypeClass = boolean.class, example = "true"),
                    @DynamicParameter(value = "返回消息", name = "msg", example = "操作成功")
            })
    )
    @PreAuthorize("@ss.hasPermi('system:plan:list')")
    @GetMapping("/api/list")
    public TableDataInfo appList(CheckPlan checkPlan) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        checkPlan.setRealUserId(user.getUserId() + "");
        return checkPlanService.selectPlanListByApp(checkPlan);
    }

    @GetMapping("/api/listN")
    public AjaxResult appListN(CheckPlan checkPlan) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        checkPlan.setRealUserId(user.getUserId() + "");
        return AjaxResult.data(AESUtils.encode(JSON.toJSONStringWithDateFormat(checkPlanService.selectPlanListByApp(checkPlan),"yyyy-MM-dd HH:mm:ss")));
    }

    @GetMapping("/api/roomList")
    public TableDataInfo roomList(CheckPlanRoom checkPlanRoom) {
        return checkPlanRoomService.selectPlanRoomListByApp(checkPlanRoom);
    }


    @GetMapping("/api/roomListN")
    public AjaxResult roomListN(CheckPlanRoom checkPlanRoom) {
        return AjaxResult.data(AESUtils.encode(JSON.toJSONStringWithDateFormat(checkPlanRoomService.selectPlanRoomListByApp(checkPlanRoom),"yyyy-MM-dd HH:mm:ss")));
    }

    @GetMapping("/api/cabinetList")
    public TableDataInfo cabinetList(CheckRoomCabinet checkRoomCabinet) {
        return checkRoomCabinetService.selectPlanCabinetListByApp(checkRoomCabinet);
    }

    @GetMapping("/api/cabinetListN")
    public AjaxResult cabinetListN(CheckRoomCabinet checkRoomCabinet) {
        return AjaxResult.data(AESUtils.encode(JSON.toJSONStringWithDateFormat(checkRoomCabinetService.selectPlanCabinetListByApp(checkRoomCabinet),"yyyy-MM-dd HH:mm:ss")));
    }
    /**
     * 盘点总进度
     */
    @GetMapping("/planCount")
    public AjaxResult planCount() {
        return AjaxResult.data(checkPlanService.selectPlanCount());
    }

}
